package com.woniuxy.house.filter;

import com.fasterxml.jackson.databind.ObjectMapper;
import com.woniuxy.house.utils.RequestThreadLocalCache;
import org.springframework.security.authentication.UsernamePasswordAuthenticationToken;
import org.springframework.security.core.Authentication;
import org.springframework.security.core.AuthenticationException;
import org.springframework.security.web.authentication.AbstractAuthenticationProcessingFilter;

import javax.servlet.ServletException;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.util.Map;

/**
 * @author baobo
 * @date 2022-08-29-11:59
 */
public class ApiUsernamePasswordAuthenticationFilter extends AbstractAuthenticationProcessingFilter {
	/**
	 * 设置登录访问路径
	 * @param defaultFilterProcessesUrl
	 */
	public ApiUsernamePasswordAuthenticationFilter(String defaultFilterProcessesUrl) {
		super(defaultFilterProcessesUrl);
	}

	@Override
	public Authentication attemptAuthentication(HttpServletRequest request, HttpServletResponse response) throws AuthenticationException, IOException, ServletException {
		//获取账号密码
		ObjectMapper mapper = new ObjectMapper();
		String paramString = RequestThreadLocalCache.getRequestFromThreadLocal();
		Map<String,String> o = mapper.readValue(paramString, Map.class);
		String username = o.get("account");
		username = (username != null) ? username.trim() : "";
		String password = o.get("password");
		password = (password != null) ? password : "";
		System.out.println(password);
		UsernamePasswordAuthenticationToken authRequest = UsernamePasswordAuthenticationToken.unauthenticated(username,
				password);
		return this.getAuthenticationManager().authenticate(authRequest);
	}
}
